package dao.imp;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;



import pojo.Customer;
import util.DBUtil;

public class FindDao {
	public static List<Customer> findAll() {
		String sql = "select id,name,sal,birth,sex from customer";
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Customer> list = new ArrayList<Customer>();
		Connection con =null;
		Customer customer;
		try {
		    con = DBUtil.createConnection();
			pst=con.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()){
				String name = rs.getString("name");
				int id = rs.getInt("id");
				Date birth = new Date(rs.getDate("birth").getTime());
				double sal = rs.getDouble("sal");
				Boolean sex = rs.getBoolean("sex");
				List<String> listHobbies = findAllHobbies(id);
				String[] str = new String[listHobbies.size()];
				listHobbies.toArray(str);
				customer =new Customer(id,name,sal,sex,birth,str);
				list.add(customer);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(con,pst,rs);
		}
		return list;
	}
	private static List<String> findAllHobbies(int m) {
		String sql = "select fav from hobby where name_id =?";
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<String> list = new ArrayList<String>();
		Connection con =null;
		try {
		    con = DBUtil.createConnection();
			pst=con.prepareStatement(sql);
			pst.setInt(1, m);
			rs = pst.executeQuery();
			while(rs.next()){
				String fav = rs.getString("fav");
				list.add(fav);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(con,pst,rs);
		}
		return list;
	}
	
}
